package pri.zjy.concurrent;

/**
 * @author zhangjy
 * @description 多线程交替打印
 * <p>
 * notify()和wait()
 * @date 2025/5/7 21:38
 */
public class AlternatePrint2 {

    static final Object monitor = new Object();

    static int num = 1;

    static int limit = 10;

    public static void main(String[] args) {
        Thread thread1 = new MyThread();
        thread1.start();
        Thread thread2 = new MyThread();
        thread2.start();
    }

}

class MyThread extends Thread {
//
//    private static  Object monitor;
//
//    public MyThread(Object monitor) {
//        this.monitor = new Object();
//    }

    @Override
    public void run() {
        synchronized (AlternatePrint2.monitor) {
            while (AlternatePrint2.num <= AlternatePrint2.limit) {

                System.out.println(getName() + "---" + AlternatePrint2.num);
                AlternatePrint2.num++;

                AlternatePrint2.monitor.notify();

                try {
                    AlternatePrint2.monitor.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                /**
                 * 这里休眠是为证明，只有当前线程synchronized释放锁后，另一个线程才有机会从wait()中唤醒！！！
                 * 而不是notify()，或notifyAll()后就会被唤醒。
                 */
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}